package com.game.doudizhu.controller;

import com.game.doudizhu.model.Friendship;
import com.game.doudizhu.model.Player;
import com.game.doudizhu.service.FriendshipService;
import com.game.doudizhu.service.PlayerService;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/friends")
public class FriendController {

    @Autowired
    private FriendshipService friendshipService;

    @Autowired
    private PlayerService playerService;

    @GetMapping("/list/{playerId}")
    public List<Player> getFriendList(@PathVariable Long playerId) {
        return friendshipService.getFriendList(playerService.getPlayer(playerId));
    }

    @GetMapping("/pending/{playerId}")
    public List<Friendship> getPendingRequests(@PathVariable Long playerId) {
        return friendshipService.getPendingRequests(playerService.getPlayer(playerId));
    }

    @GetMapping("/pending/{playerId}/count")
    public int getPendingRequestCount(@PathVariable Long playerId) {
        return friendshipService.getPendingRequests(playerService.getPlayer(playerId)).size();
    }

    @PostMapping("/request/byUsername")
    public Friendship sendFriendRequestByUsername(
            @RequestParam String username,
            @RequestParam Long playerId) {
        Player sender = playerService.getPlayer(playerId);
        Player receiver = playerService.findByUsername(username);
        return friendshipService.sendFriendRequest(sender, receiver);
    }

    @PostMapping("/accept/{requestId}")
    public Friendship acceptFriendRequest(@PathVariable Long requestId) {
        return friendshipService.acceptFriendRequest(requestId);
    }

    @DeleteMapping("/reject/{requestId}")
    public void rejectFriendRequest(@PathVariable Long requestId) {
        friendshipService.rejectFriendRequest(requestId);
    }

    @DeleteMapping("/remove/{friendId}")
    public void removeFriend(@PathVariable Long friendId, @RequestParam Long playerId) {
        Player player = playerService.getPlayer(playerId);
        Player friend = playerService.getPlayer(friendId);
        friendshipService.removeFriend(player, friend);
    }

}